package org.twdata.pipeline.stage;

import java.io.StringWriter;
import java.io.Writer;
import javax.xml.transform.*;
import javax.xml.transform.dom.*;
import javax.xml.transform.sax.*;

import org.twdata.pipeline.*;

// SAX imports:
import org.xml.sax.Attributes;
import org.xml.sax.ContentHandler;
import org.xml.sax.Locator;
import org.xml.sax.SAXException;
import org.xml.sax.ext.LexicalHandler;

/**  Serializes SAX events into a DOM node.  */
public class DOMSerializer extends AbstractSerializer implements Serializer {

    private SAXTransformerFactory tfactory;
    private TransformerHandler handler = null;
    private DOMResult result;
    private PipelineContext ctx;


    /**
     *  Sets up the serializer for the current context
     *
     *@param  ctx                    The context information
     *@exception  PipelineException  If something goes wrong
     */
    public void setup(PipelineContext ctx)
        throws PipelineException {

        try {
            if (tfactory == null) {
                tfactory = (SAXTransformerFactory)TransformerFactory.newInstance();
                tfactory.setErrorListener(new TraxErrorListener());
            }
            handler = tfactory.newTransformerHandler();
        } catch (Exception ex) {
            throw new PipelineException(ex);
        }
        contentHandler = handler;
        lexicalHandler = handler;
        Result res = ctx.getResult();
        if (res instanceof DOMResult) {
            result = (DOMResult)res;
        } else {
            throw new PipelineException("Result type not supported");
        }
        handler.setResult(result);

        this.ctx = ctx;
    }


    /**  Recycle instances */
    public void recycle() {
        result = null;
        handler = null;
        ctx = null;
    }


    /**
     *  Receive notification of the end of a document.
     *
     *@exception  SAXException  If anything goes wrong
     */
    public void endDocument()
        throws SAXException {
        super.endDocument();
    }
}

